const fs = require('fs');
const path = require('path');

class PerformanceMonitor {
    constructor() {
        this.metrics = {
            buildTime: 0,
            bundleSize: 0,
            testCoverage: 0,
            memoryUsage: 0,
            startupTime: 0
        };
        this.thresholds = {
            buildTime: 300000, // 5分钟
            bundleSize: 5 * 1024 * 1024, // 5MB
            testCoverage: 80, // 80%
            memoryUsage: 100 * 1024 * 1024, // 100MB
            startupTime: 3000 // 3秒
        };
    }

    async measureBuildTime(buildFunction) {
        const startTime = Date.now();
        await buildFunction();
        this.metrics.buildTime = Date.now() - startTime;
        return this.metrics.buildTime;
    }

    measureBundleSize(distPath) {
        const stats = this.getDirectorySize(distPath);
        this.metrics.bundleSize = stats;
        return stats;
    }

    getDirectorySize(dirPath) {
        let totalSize = 0;
        const files = fs.readdirSync(dirPath);
        
        files.forEach(file => {
            const filePath = path.join(dirPath, file);
            const stats = fs.statSync(filePath);
            
            if (stats.isDirectory()) {
                totalSize += this.getDirectorySize(filePath);
            } else {
                totalSize += stats.size;
            }
        });
        
        return totalSize;
    }

    checkThresholds() {
        const violations = [];
        
        Object.keys(this.thresholds).forEach(metric => {
            if (this.metrics[metric] > this.thresholds[metric]) {
                violations.push({
                    metric,
                    actual: this.metrics[metric],
                    threshold: this.thresholds[metric]
                });
            }
        });
        
        return violations;
    }

    generateReport() {
        const violations = this.checkThresholds();
        const report = {
            timestamp: new Date().toISOString(),
            metrics: this.metrics,
            thresholds: this.thresholds,
            violations: violations,
            status: violations.length === 0 ? 'PASS' : 'FAIL'
        };

        // 保存报告
        const reportPath = path.join(__dirname, '..', 'performance-reports');
        if (!fs.existsSync(reportPath)) {
            fs.mkdirSync(reportPath, { recursive: true });
        }

        const fileName = `performance-${Date.now()}.json`;
        fs.writeFileSync(
            path.join(reportPath, fileName),
            JSON.stringify(report, null, 2)
        );

        return report;
    }
}

module.exports = PerformanceMonitor;